import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_upgrade/upgrade.dart';

import 'flutter_upgrade_platform_interface.dart';

class FlutterUpgrade {
  var dio = Dio();

  Future<String?> getPlatformVersion() {
    return FlutterUpgradePlatform.instance.getPlatformVersion();
  }

  void upgrade (
      BuildContext context, int buildNumber, String deviceId, String appId, {String url = "https://oapi.jarvisgo.cn/pos/posTerminal/findUpdateVersion"}) {
    _checkVersion(buildNumber, deviceId, appId, url).then((response) {
      final forcedUpgrade = response.data["data"]["force"];
      final url = response.data["data"]["update_url"];
      final des = response.data["data"]["change_log"];
      if (response.data["data"] != null) {
        Navigator.of(context).push(
          PageRouteBuilder(
              opaque: false,
              pageBuilder: (context, animation, secondaryAnimation) {
                return Upgrade(forcedUpgrade, url, des, appId);
              }),
        );
      }
    });
  }

  Future<Response> _checkVersion(
      int buildNumber, String deviceId, String appId, String url) async {
    dio.options.headers = {"deviceId": deviceId};
    var response = await dio.post(
        url,
        data: {"build_number": buildNumber, "app_id": appId});
    return response;
  }
}
